'use strict';

// 分布条数
var limit = 5;
var role = 999;
var interval = 60;
var roles = [];
var user;
var version = '3.0.123123';
var pay_type = 'alipay_pc_direct';
var firstload = 1;
var isweixin = false;
// var pay_type = 'alipay_wap';

// Declare app level module which depends on views, and components
// create module
var app = angular.module('5wutian', [
    'oc.lazyLoad',
    'ngTouch',
    'ui.router',
    'ngStorage',
    'ui.bootstrap'
]);

var ua = navigator.userAgent;
var ipad = ua.match(/(iPad).*OS\s([\d_]+)/),
    isIphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/),
    isAndroid = ua.match(/(Android)\s+([\d.]+)/),
    isMobile = isIphone || isAndroid;

if (isMobile) {
    pay_type = 'alipay_wap';
}

function isWeiXin() {
    if (ua.toLowerCase().match(/MicroMessenger/i) == 'micromessenger') {
        isweixin = true;
        return true;
    } else {
        isweixin = false;
        return false;
    }
}
var isweixin = isWeiXin();

app.run(['$rootScope', '$state', '$stateParams', '$localStorage', '$location', function($rootScope, $state, $stateParams, $localStorage, $location) {
    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams;
    $rootScope.limit = limit;
    $rootScope.maxSize = 5;
    $rootScope.alert = {
        close: false,
        tpl: 'content'
    };
    $rootScope.issetting = false;
    
    // 'tech', 'business', 'finance', 'cashier'
    $rootScope.handleLists = {
        or: ['edit_order'],
        order: ['manager', 'edit_order', 'finance'],
        all: ['manager', 'edit_order', 'edit_amount', 'commission', 'finance'],
        amount_roles: ['manager', 'finance', 'edit_amount']
    };

    $rootScope.mobile = !!ua.match(/AppleWebKit.*Mobile.*/) || false;

    $rootScope.logout = function() {
        $state.go('home', {}, { reload: true });
        $localStorage.user = {};
        $localStorage.mutian_token = '';
    };

    var urls_data = ['register', 'service', 'brand', 'reservation']
    $rootScope.$on('$stateChangeSuccess',
        function(event, toState, toParams, fromState, fromParams) {
            $rootScope.token = $localStorage.mutian_token;
            $rootScope.user = user = $localStorage.user;

            // 头部列表
            if (user) {
                $rootScope.user_role = role = user.role;
            }
            // console.log('event, toState, toParams, fromState, fromParams', toState.name, toParams, fromState, fromParams)
            $localStorage.mobile_href = $location.absUrl();
            if(!isweixin) {
                var data_type = toState.name.split('.')[0];
                var data = $localStorage.data_save;
                var index = urls_data.indexOf(data_type);
                if(index != -1 && data.data_type == data_type) {
                } else {
                    $localStorage.data_save = '';
                }
            }
        });

    $rootScope.$on('$stateChangeStart',
        function(event, toState, toParams, fromState, fromParams) {
            $rootScope.token = $localStorage.mutian_token;
            // event.preventDefault();
            var href = $localStorage.mobile_href;
            // if(href && firstload == 1 && isMobile && !isweixin) {
            //     ++firstload;
            //     // console.log('href && firstload == 1 && isMobile && !isweixin', href, firstload, isMobile, isweixin, href && firstload == 1 && isMobile && !isweixin)
            //     // window.location.href = href;
            // }
        });

    $rootScope.goBack = function(num) {
        window.history.go(num || -1);
    };

    $rootScope.toggleSide = function(bool) {
        $('.left-menu-side').toggleClass('active', bool);
        $('.right-menu-side').toggleClass('active', bool);
    };

    $rootScope.closeMenu = function() {
        if (isMobile) {
            document.getElementById("headerpersion").click()
        }
    };

    $rootScope.ToggleAlert = function() {
        $rootScope.issetting = !$rootScope.issetting;
    };

}]);

app.factory('myInterceptor', [
    '$injector', '$localStorage', '$rootScope',
    function($injector, $localStorage, $rootScope) {
        var httpInterceptor;
        httpInterceptor = {
            request: function(config) {

                if (config.url.substr(config.url.length - 5) != '.html') {
                    config.headers.Authorization = $localStorage.mutian_token;
                }
                return config;
            },
            response: function(response) {
                var rootScope;
                if (response.config.url.substr(response.config.url.length - 5) != '.html') {
                    if (response.status === 200) {
                        if (parseInt(response.data.code, 10) == 419) {
                            rootScope = $injector.get('$rootScope');
                            rootScope.$state.go('login');
                            $localStorage.$reset = {};
                        }
                        return response;
                    } else {
                        if (parseInt(response.data.code, 10) == 419) {
                            rootScope = $injector.get('$rootScope');
                            rootScope.$state.go('login');
                            $localStorage.$reset = {};
                        }
                        return response;
                    }
                } else {
                    return response;
                }
            },
            error: function(error) {
                console.log('error', error)
            }
        };
        return httpInterceptor;
    }
]);

app.config(['$urlRouterProvider', '$locationProvider', '$httpProvider', function($urlRouterProvider, $locationProvider, $httpProvider) {
    // $locationProvider.hashPrefix('!');
    $httpProvider.interceptors.push('myInterceptor');
    $urlRouterProvider.otherwise('/home');
    $locationProvider.html5Mode(true);
}]);

app.controller('headerCtrl', ['$scope', 'httpService', '$localStorage', 'role', '$state', '$rootScope', 'alertmsg', function($scope, httpService, $localStorage, role, $state, $rootScope, alertmsg) {


    $rootScope.$on('$stateChangeSuccess',
        function(event, toState, toParams, fromState, fromParams) {
            if ($localStorage.user) {
                updateLeft();
            }
        });

    $scope.brandmanagerlist = [
        { name: '邀请成员', icon: 'yaoqing', params: 'invite' },
        { name: '管理成员', icon: 'guanli', params: 'management' }
    ];



    function updateLeft(user) {
        $scope.mineListByRole = role.get($localStorage.user);
        $scope.defaultlist = [
            { name: '个人资料', icon: 'ziliao', params: 'zoom,uploadCtrl,personal' },
            { name: '账号设置', icon: 'anquan', params: 'setting' }
        ];
        if ($localStorage.user && (($localStorage.user.user_type == 'finance' && $localStorage.user.company_id) || !$localStorage.user.company_id)) {
            $scope.defaultlist = $scope.defaultlist.concat({ name: '通讯目录', icon: 'tongxunlu', params: 'contacts' });
        }
        if($localStorage.user && $localStorage.user.user_type == 'finance') {
            $scope.defaultlist = $scope.defaultlist.concat({ name: '发票管理', icon: 'fapiao', params: 'invoice' });
        }
        if ($localStorage.user && $localStorage.user.role == 1 && $localStorage.user.user_type == 'manager') {
            var obj = [
                { name: '渠道管理', icon: 'qudao', params: 'canal' },
                // { name: '品牌管理', icon: 'pinpai', params: 'enterprise' },
                { name: '更多功能', icon: 'more', params: 'functions' }
            ];
            angular.forEach($localStorage.user.addons, function(v, k) {
                if(v.serial_number == '5mutian_brand_manage') {
                    obj.splice(1, 0, { name: '品牌管理', icon: 'pinpai', params: 'enterprise' });
                }
            });
            $scope.defaultlist = $scope.defaultlist.concat(obj);
        }
    }
    updateLeft();

    $scope.select = function(r) {
        if (r.name == '我的钱包') {
            if (($state.includes('mine.recharge') || $state.includes('mine.cash'))) {
                return true;
            }
            return false;
        } else if (r.name == '我的订单') {
            if ($state.includes('mine.orderdetail')) {
                return true;
            }
            return false;
        } else if (r.name == '审核订单') {
            if ($state.includes('mine.revieworder')) {
                return true;
            }
            return false;
        }
    };

    function getPersion(id) {
        httpService.query('web/users/' + id).then(function(res) {
            if (res.code == 200) {
                $localStorage.user = $rootScope.user = res.user;
            }
        });
    };
}]);

var statesArrs = [
    { name: '新订单', state: 'new' },
    { name: '预约测量', state: 'appointed_measurement' },
    { name: '已测量', state: 'measured' },
    { name: '预约安装', state: 'appointed_installation' },
    { name: '已安装', state: 'installed,confirm_installed' },
    { name: '已完成', state: 'completed' }
    // ,{ name: '已取消', state: 'canceled' },
];

var statesArrs2 = statesArrs.concat([{ name: '已取消', state: 'canceled' }]);


var user_types = [
    // { in : 'server', name: '客服' },
    { in : 'user', name: '普通用户' },
    { in : 'manager', name: '管理员' },
    { in : 'tech', name: '技术' },
    { in : 'business', name: '商务' },
    { in : 'finance', name: '财务' },
    { in : 'cashier', name: '出纳' },
    { in : 'super', name: '超级用户' },
    { in : 'dealer', name: '经销商' }
];

$(function() {
    $('.mycollapse').on('click', function() {
        $(this).removeClass('in');
    });

    window.Modal = function() {
        var reg = new RegExp("\\[([^\\[\\]]*?)\\]", 'igm');
        var alr = $("#ycf-alert");
        var ahtml = alr.html();

        //关闭时恢复 modal html 原样，供下次调用时 replace 用
        //var _init = function () {
        //  alr.on("hidden.bs.modal", function (e) {
        //      $(this).html(ahtml);
        //  });
        //}();

        /* html 复原不在 _init() 里面做了，重复调用时会有问题，直接在 _alert/_confirm 里面做 */


        // var _alert = function(options) {
        //     alr.html(ahtml); // 复原
        //     alr.find('.ok').removeClass('btn-success').addClass('btn-primary');
        //     alr.find('.cancel').hide();
        //     _dialog(options);

        //     return {
        //         on: function(callback) {
        //             if (callback && callback instanceof Function) {
        //                 alr.find('.ok').click(function() { callback(true) });
        //             }
        //         }
        //     };
        // };

        var _confirm = function(options) {
            alr.html(ahtml); // 复原
            alr.find('.ok').removeClass('btn-primary').addClass('btn-success');
            alr.find('.cancel').show();
            _dialog(options);

            return {
                on: function(callback) {
                    if (callback && callback instanceof Function) {
                        alr.find('.ok').click(function() { callback(true) });
                        alr.find('.cancel').click(function() { callback(false) });
                    }
                }
            };
        };

        var _dialog = function(options) {
            var ops = {
                msg: "提示内容",
                title: "操作提示",
                btnok: "确定",
                btncl: "取消"
            };

            $.extend(ops, options);

            var html = alr.html().replace(reg, function(node, key) {
                return {
                    Title: ops.title,
                    Message: ops.msg,
                    BtnOk: ops.btnok,
                    BtnCancel: ops.btncl
                }[key];
            });

            alr.html(html);
            alr.modal({
                width: 500,
                backdrop: 'static'
            });
        }

        return {
            // alert: _alert,
            confirm: _confirm
        }

    }();

});
